<template>
  <div class="full-box">
    <!-- 地图-计算资源配置 -->
    <div class="gplot-box"></div>
    <div class="page-back-box" @click="goBack"><span class="back-icon"></span> 返回</div>

    <div class="select-box">
      <SchemeSelect
        :placeholder="state.placeholderOne"
        :define-options="state.optionsOne"
        :images="'u97.png'"
        @changeSelect="changeSelect"
      />
      <SchemeList
        class="marg-top"
        ref="schemeListRef"
        :show-list="false"
        @clickLi="clickLi"
        @handleAdd="handleAdd"
        :images="'u101.png'"
        :title="'计算资源'"
        :data-list="state.dataList"
        :btn-name="state.btnName"
        v-if="!showAddUnit"
      >
        <div class="ul-box">
          <!-- <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleChangeTab" stretch>
            <el-tab-pane label="水文" name="first"> -->
          <ul v-if="!state.flag">
            <li
              :class="['item-li', currentLi === index ? 'active' : '']"
              :key="index"
              v-for="(item, index) in state.resourceZoneList"
              @click="clickLi(item, index)"
            >
              <el-tooltip
                :content="item.reszName"
                placement="bottom"
                :disabled="item.reszName?.length < 7"
              >
                <span>{{ item.reszName }}</span>
              </el-tooltip>
              <span class="update-icon" @click.stop="handleUpdateArea(item)">
                <el-icon>
                  <Edit />
                </el-icon>
              </span>
              <span class="close-icon" @click.stop="handleDeleteArea(item)">X</span>
            </li>
          </ul>
          <ul v-else>
            <!-- 返回到区按钮 -->
            <i :class="['back-icon', 'z-index']" @click="handleBack()">
              <el-icon>
                <Back />
              </el-icon>
            </i>
            <li
              :class="['item-li', currentLiGroup === index ? 'active' : '']"
              :key="index"
              v-for="(item, index) in state.groupList"
              @click="clickLiGroup(item, index)"
            >
              <!-- <i class="back-icon" @click.stop="handleBack(item)">
                    <el-icon>
                      <Back />
                    </el-icon>
                  </i>-->
              <el-tooltip
                :content="item.groupName"
                placement="bottom"
                :disabled="item.groupName?.length < 7"
              >
                <span>{{ item.groupName }}</span>
              </el-tooltip>
              <!-- 组详情，编辑 -->
              <span class="update-icon" @click.stop="handleDetailsGroup(item)">
                <el-icon>
                  <Edit />
                </el-icon>
              </span>
              <!-- 删除组 -->
              <span class="close-icon" @click.stop="handleDeleteGroup(item)">X</span>
            </li>
          </ul>
          <!-- </el-tab-pane> -->
          <!-- <el-tab-pane label="水动力" name="second">
              <ul>
                <li
                  :class="['item-li', currentLi === index ? 'active' : '']"
                  :key="index"
                  v-for="(item, index) in state.riverList"
                  @click="clickLi(item, index)"
                >
                  <el-tooltip
                    :content="item.rsysName"
                    placement="bottom"
                    :disabled="item.rsysName?.length < 7"
                  >
                    <span>{{ item.rsysName }}</span>
                  </el-tooltip>

                  <span class="close-icon" @click.stop="handleDeleteRiver(item)">X</span>
                </li>
              </ul>
            </el-tab-pane> -->
          <!-- </el-tabs> -->
        </div>
      </SchemeList>
      <!-- <SchemeList @clickLi="clickLi" @handleAdd="handleSaveUnit" :images="'u101.png'" :show-list="false" :title="'单元组1'"
        :data-list="state.dataList" :btn-name="'保存并返回'" v-else>
        <div class="add-box">
          <div class="unit-box">
            <div class="title">所属计算单元(点选)</div>
            <div class="unit-list">
              <div class="unit-li" :key="index" v-for="(item, index) in state.checkedArr">
                <span>{{ item.label }}</span>
                <span @click="handleDeleteNode(item)">X</span>
              </div>
            </div>
          </div>
          <div class="node-box">
            <div class="title">所属计算节点</div>
            <el-select placeholder="请输入">
              <el-option label="192.168.0.2" value="shanghai" />
              <el-option label="192.168.0.1" value="beijing" />
            </el-select>
          </div>
        </div>
      </SchemeList>-->
    </div>
    <!-- 新建单元组 -->
    <el-dialog width="30%" v-model="dialogVisible" title="新建单元组" :before-close="handleClose">
      <div class="unit-box">
        <div class="form-box">
          <span>单元组名称：</span>
          <el-input v-model="schemeName" placeholder="请输入"></el-input>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleSave">确定</el-button>
          <el-button @click="handleClose()">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 新建单元区 -->
    <el-dialog width="30%" v-model="dialog2Visible" title="新建计算组" :before-close="handle2Close">
      <div class="unit-box">
        <el-form ref="formRef" :model="formInline" label-width="auto">
          <el-form-item label="所属计算区：">
            <el-select v-model="formInline.area" placeholder="所属计算区">
              <el-option label="区一" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计算节点：">
            <el-input class="w400" v-model="formInline.node" placeholder="计算节点"></el-input>
          </el-form-item>
          <el-form-item label="组名称：">
            <!-- <el-select v-model="schemeName" placeholder="组名称">
              <el-option label="水文" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>-->
            <el-input class="w200" v-model="formInline.name" placeholder></el-input>
          </el-form-item>
          <el-form-item label="开始断面：">
            <el-select v-model="formInline.obj" placeholder>
              <el-option label="杨家横、乔店" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="结束断面：">
            <el-select v-model="formInline.obj" placeholder>
              <el-option label="杨家横、乔店" value="shanghai"></el-option>
              <el-option label="区域二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handle2Save">确定</el-button>
          <el-button @click="handle2Close()">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <div id="container"></div>
    <!-- <div class="btn-box">
      <el-button type="primary" @click="handleClickNode">节点管理</el-button>
    </div> -->
    <NodeManage v-if="state.hiddenFlag" />
    <AreaModel ref="areamodelRef" @closeDialog="closeDig" />
    <GroupModel ref="groupmodelRef" @closeDialog="handleBack" />
  </div>
</template>
<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import SchemeList from '@/components/app-publicui/scheme-list.vue'
import { getMapAssetURL } from '@/utils/loadAssets'
import { idsArr, idsArr1, idsArr2, idsArr3, idsArr4 } from './ids.js'
import sec_topology from '@/assets/data/com_data/sec_topology.json'
import NodeManage from './cpns/nodeManage/index.vue'
//新增计算区
import AreaModel from './cpns/areaModel/index.vue'
//新增计算组
import GroupModel from './cpns/groupModel/index.vue'
//接口
import {
  getResourceZone,
  getResourceGroupInfos,
  getResourceSec,
  deleteResourceZone,
  // 删除水文计算分组
  deleteResourceGroupInfos
} from '@/services/modules/base-config'
import { getZone } from '@/services/modules/model-config'
import G6 from '@antv/g6'
import emitter from '@/utils/bus'
import { ElMessage, ElMessageBox } from 'element-plus'
//选中
const currentLi = ref(null)
const zoneId = ref(1)
const currentLiGroup = ref(null)
const dialog2Visible = ref(false)
const dialogVisible = ref(false)
const showAddUnit = ref(false)
const schemeListRef = ref(null)
const activeName = ref('first')
//计算区
const areamodelRef = ref(null)
//计算组
const groupmodelRef = ref(null)
const formRef = ref(null)
const state = reactive({
  flag: false,
  //水文资源分区
  resourceZoneList: [],
  //计算组
  groupList: [],

  btnName: '新建计算区',
  hiddenFlag: false,
  graph: '',
  sec_topologData: {},
  checkedArr: [],
  dataList: [
    {
      title: '角峪桥单元组',
      id: 1
    },
    {
      title: '楼德单元组',
      id: 2
    },
    {
      title: '北望单元组',
      id: 3
    },
    {
      title: '尚庄炉单元组',
      id: 4
    },
    {
      title: '东平湖单元组',
      id: 5
    }
  ],
  placeholder: '大汶河优选方案',
  // 选中的水文区id
  groupItem: {}
})
let formInline = reactive({
  area: '',
  node: '',
  name: '',
  obj: ''
})
const goBack = () => {
  emitter.emit('goback', true)
}
const imageArr = {
  2: getMapAssetURL('sw.svg'),
  1: getMapAssetURL('sk.svg')
}
emitter.on('closePage', (value) => {
  state.hiddenFlag = false
})
//
async function closeDig() {
  await initData()
  state.graph.refresh()
}
//切换zone（大汶河）
const changeSelect = (v) => {
  zoneId.value = v
  //获取水文资源区
  getResourceZone({ zoneId: zoneId.value }).then((res) => {
    if (res.code === 200) {
      state.resourceZoneList = res.data
      clickLi(state.resourceZoneList[0], 0)
    }
  })

  // initData()
}
// function handleChangeTab(val) {
//   activeName.value = val
//   if (val == 'first') {
//     // state.btnName = '新建区域'
//   } else if (val == 'second') {
//     // state.btnName = '新建河系'
//     // rsysList()
//   }
// }
//点击节点管理
function handleClickNode() {
  state.hiddenFlag = true
}
function getZoneList() {
  return new Promise((resolve, reject) => {
    getZone().then((res) => {
      if (res.code === 200) {
        state.optionsOne = res.data
        zoneId.value = res.data[0].id
        //  initData()
        resolve(zoneId.value)
      }
    })
  })
}
async function initData() {
  //获取水文资源区
  getResourceZone({ zoneId: zoneId.value }).then((res) => {
    if (res.code === 200) {
      state.resourceZoneList = res.data
    }
  })
  getResourceSec({ zoneId: zoneId.value }).then((res) => {
    if (res.code === 200) {
      state.sec_topologData.nodes = res.data.map((item) => {
        return {
          id: item.blkcd,
          label: item.blknm,
          pmt: 1
        }
      })
      state.sec_topologData.edges = res.data.map((vItem) => {
        return {
          source: vItem.blkcd,
          target: vItem.ocd
        }
      })
      // initG6([])
    }
  })
  // state.sec_topologData.nodes = sec_topology.sec
  // state.sec_topologData.edges = sec_topology.topology
  // debugger
  // state.sec_topologData.nodes = state.sec_topologData.nodes.map((item) => {
  //   return {
  //     id: item.blkcd,
  //     label: item.blknm,
  //     pmt: item.pmt
  //   }
  // })
  // state.sec_topologData.edges = state.sec_topologData.edges.map((vItem) => {
  //   return {
  //     source: vItem.inblkcd,
  //     target: vItem.outblkcd
  //   }
  // })
}
// 初始化 G6
const handleInitG6 = () => {
  const container = document.getElementById('container')
  const width = container.clientWidth
  const height = container.clientHeight
  state.graph = new G6.Graph({
    container: container,
    width: width,
    height: height,
    fitView: true,
    // "animate":true,
    fitViewPadding: [16, 16, 16, 16],
    modes: {
      default: ['zoom-canvas', 'drag-canvas', 'brush-select', 'node-select', 'click-select']
      // edit: ['click-select']
    },
    layout: {
      type: 'dagre',
      rankdir: 'TB',
      align: ''
    },
    defaultNode: {
      type: 'modelRect',
      style: {
        fill: '#ffffff',
        stroke: '#169bd5',
        cursor: 'pointer',
        width: 170,
        height: 60
      },
      preRect: {
        // 设置为false，则不显示
        show: false,
        fill: '#f759ab',
        width: 8
      },
      stateIcon: {
        show: false
      },
      labelCfg: {
        position: 'center',
        style: {
          textAlign: 'center',
          fontStyle: 'normal',
          color: '#169bd5'
        },

        offset: 80
      },
      anchorPoints: [
        [0.5, 0],
        [0.5, 1]
      ]
    },
    defaultEdge: {
      type: 'polyline',
      color: '#169bd5',
      style: {
        // "stroke": "rgb(79, 79, 79)",
        endArrow: {
          $arrowType: 'diy',
          $path: 'M 0,0 L 10,5 L 10,-5 Z',
          $compute: (e) => e,
          path: 'M 0,0 L 10,5 L 10,-5 Z',
          d: 5,
          fill: '#4a90e2',
          stroke: '#4a90e2'
        },
        cursor: 'default',
        //  "offset": 0  ,
        startArrow: {
          path: ''
        }
      }
    },
    nodeStateStyles: {
      // 鼠标 hover 上节点，即 hover 状态为 true 时的样式
      hover: {
        fill: 'lightsteelblue'
      },
      // 鼠标点击节点，即 click 状态为 true 时的样式
      click: {
        fill: 'lightsteelblue'
      }
    },
    // 节点不同状态下的样式集合
    edgeStateStyles: {
      // 鼠标点击边，即 click 状态为 true 时的样式
      click: {
        stroke: 'steelblue'
      }
    }
  })
}
//返回计算区
function handleBack() {
  console.log('区')
  state.flag = false
  state.btnName = '新建计算区'
  currentLiGroup.value = null
}
function clickLi(item, index) {
  state.flag = true
  currentLi.value = index
  state.btnName = '新建计算组'
  // 选中的水文区
  state.groupItem = item
  getResourceGroupInfos({ zid: item.id }).then((res) => {
    if (res.code === 200) {
      // 获取组列表 并将区id放置组列表中
      res.data?.groups.map((e) => {
        e.zid = res.data.zid
      })
      state.groupList = res.data?.groups
      clickLiGroup(state.groupList[0], 0)
    }
  })
  // if (item.id == 1) {
  //   initG6(idsArr)
  // } else if (item.id == 2) {
  //   initG6(idsArr1)
  // } else if (item.id == 3) {
  //   initG6(idsArr2)
  // } else if (item.id == 4) {
  //   initG6(idsArr3)
  // } else if (item.id == 5) {
  //   initG6(idsArr4)
  // }
}
function clickLiGroup(item, index) {
  if (item?.secs.length && state.graph) {
    initG6(item.secs)
    state.graph.refresh()
  }
  currentLiGroup.value = index
}
//删除资源分区
function handleDeleteArea(item) {
  ElMessageBox.confirm(`是否删除${item.reszName}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteResourceZone({ id: item.id }).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg)
          initData()
        }
      })
    })
    .catch(() => {})
}
// 回显编辑组 item:组信息。
function handleDetailsGroup(item) {
  console.log('编辑组', item)
  // 打开编辑组弹框
  groupmodelRef.value.handleOpenModal(item)
}
// 删除组
function handleDeleteGroup(item) {
  ElMessageBox.confirm(`是否删除${item.groupName}`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteResourceGroupInfos({ id: item.id }).then((res) => {
        if (res.code == 200) {
          ElMessage.success(res.msg)
          clickLi(state.groupItem, currentLi)
        }
      })
    })
    .catch(() => {})
}
//修改资源分区
function handleUpdateArea(item) {
  areamodelRef.value.handleOpenModal(item)
}
//新建计算区或计算组
function handleAdd(index) {
  if (state.btnName == '新建计算区') {
    areamodelRef.value.handleOpenModal()
  } else if (state.btnName == '新建计算组') {
    groupmodelRef.value.handleOpenModal()
  }
}
//新建保存
function handleSave() {
  showAddUnit.value = true
  dialogVisible.value = false
}
//取消新建
function handleClose() {
  dialogVisible.value = false
}
function handle2Close() {
  dialog2Visible.value = false
  formRef.value.resetFields()
}
//保存单元
function handleSaveUnit() {
  showAddUnit.value = false
  graph.setMode('edit')
}
//删除节点
function handleDeleteNode(value) {
  state.checkedArr = state.checkedArr.filter((item) => {
    return item.id != value.id
  })
}
function initG6(idsArr) {
  state.graph.node((node) => {
    if (
      idsArr.filter((item) => {
        return item.blkcd == node.id
      }).length > 0
    ) {
      return {
        id: node.id,
        type: 'modelRect',
        logoIcon: {
          // 是否显示icon，值为 false 则不渲染icon
          show: true,
          x: 0,
          y: 0,
          // icon的地址，字符串类型
          img: imageArr[node.pmt],
          width: 16,
          height: 16,
          // 用于调整图标的左右位置
          offset: 0
        },
        style: {
          fill: '#D6F9A5'
        }
        // labelCfg: {
        //   style: {
        //     fill: 'orange'
        //   }
        // },
      }
    } else {
      return {
        id: node.id,
        type: 'modelRect',
        logoIcon: {
          // 是否显示icon，值为 false 则不渲染icon
          show: true,
          x: 0,
          y: 0,
          // icon的地址，字符串类型
          img: imageArr[node.pmt],
          width: 16,
          height: 16,
          // 用于调整图标的左右位置
          offset: 0
        },
        style: {
          fill: '#96C94B'
        }
      }
    }
  })
  console.log('666', state.sec_topologData)

  // 读取数据
  state.graph.data(state.sec_topologData)
  // 渲染图
  state.graph.render()
  // // 鼠标进入节点
  // state.graph.on('node:mouseenter', (e) => {
  //   const nodeItem = e.item // 获取鼠标进入的节点元素对象
  //   state.graph.setItemState(nodeItem, 'hover', true) // 设置当前节点的 hover 状态为 true
  // })

  // // 鼠标离开节点
  // state.graph.on('node:mouseleave', (e) => {
  //   const nodeItem = e.item // 获取鼠标离开的节点元素对象
  //   state.graph.setItemState(nodeItem, 'hover', false) // 设置当前节点的 hover 状态为 false
  // })
  // 点击节点
  // state.graph.on('node:click', (e) => {
  //   // // 先将所有当前是 click 状态的节点置为非 click 状态
  //   const clickNodes = state.graph.findAllByState('node', 'click')
  //   console.log(clickNodes)
  //   const nodeItem = e.item // 获取被点击的节点元素对象
  //   state.graph.setItemState(nodeItem, 'click', true) // 设置当前节点的 click 状态为 true
  //   clickNodes.forEach((cn) => {
  //     console.log(cn, e)
  //     if (cn._cfg.id == e.item._cfg.id) {
  //       state.graph.setItemState(cn, 'click', false)
  //     }
  //   })
  //   console.log('111', state.graph.findAllByState('node', 'click'))

  //   let arr = state.graph.findAllByState('node', 'click')
  //   state.checkedArr = arr.map((item) => {
  //     return {
  //       id: item._cfg.model.id,
  //       label: item._cfg.model.label
  //     }
  //   })
  // })
}
onMounted(async () => {
  await getZoneList()
  await initData()
  handleInitG6()
  //  getZoneList()

  // schemeListRef.value.defineChecked()

  // initG6([])
})
</script>
<style lang="less" scoped>
.ul-box {
  height: 100%;
  .demo-tabs {
    height: 100%;
    :deep(.el-tabs__content) {
      height: calc(100% - 55px);
      .el-tab-pane {
        height: 100%;
      }
    }
  }
  .back-icon {
    color: white;
    position: absolute;
    left: 5px;
  }
  .z-index {
    z-index: 1000;
  }
  ul {
    height: 230px;
    overflow-y: auto;
    font-size: 14px;
    .item-li {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 35px;
      position: relative;

      cursor: pointer;
      span {
        color: white;
      }
      span:nth-of-type(1) {
        max-width: 200px; //也可以设置最大宽度
        overflow: hidden; //溢出隐藏
        white-space: nowrap; // 强制一行显示
        text-overflow: ellipsis; // 显示。。。省略号
      }
      .close-icon {
        color: red;
        position: absolute;
        right: 2px;
      }
      .update-icon {
        color: white;
        position: absolute;
        right: 15px;
      }
      .back-icon {
        color: white;
        position: absolute;
        left: 5px;
      }
      &.active {
        span {
          color: #00d3e9;
        }
        .close-icon {
          color: red;
          position: absolute;
          right: 2px;
        }
        .update-icon {
          color: white;
          position: absolute;
          right: 15px;
        }
        .back-icon {
          color: white;
          position: absolute;
          left: 5px;
        }
      }
    }
  }
}
.gplot-box {
  width: 100%;
  height: 100%;
  // background-color: #f5f5f5;
  background-color: #1b3267;
}
.btn-box {
  position: absolute;
  top: 10px;
  right: 100px;
}
.select-box {
  width: 200px;
  position: absolute;
  top: 50px;
  left: 30px;
  .marg-top {
    margin-top: 20px;
  }
  .add-box {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    padding: 20px 20px 10px 10px;
    .unit-box {
      height: 50%;
      .title {
        color: #7f7f7f;
        height: 20px;
      }
      .unit-list {
        height: calc(100% - 30px);
        box-sizing: border-box;
        overflow-y: auto;
        padding-left: 5px;
        .unit-li {
          display: flex;
          justify-content: space-between;
          span:nth-of-type(1) {
            color: #169bd5;
          }
          span:nth-of-type(2) {
            color: red;
            cursor: pointer;
          }
        }
      }
    }
    .node-box {
      height: 50%;
      .title {
        color: #7f7f7f;
      }
      .el-select {
        // margin: 0 10px;
        padding: 10px;
      }
    }
  }
}
#container {
  position: absolute;
  left: 19%;
  top: 50px;
  width: 80%;

  height: 80%;
  border: 1px solid #149bd5;
}
.unit-box {
  .form-box {
    margin-bottom: 10px;
    .el-input {
      width: 300px;
    }
  }
}
.w200 {
  width: 200px;
}
.w400 {
  width: 400px;
}
.full-box {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
